package org.alino.core.shiro.filter;

import org.alino.core.utils.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Desc 权限校验 Filter
 * @Author by Brant
 * @Date 2017/1/13
 */
public class PermissionFilter extends AccessControlFilter {
    private String loginUrl;
    private String unauthorizedUrl;
    private String suffix;
    private static final String URL_LOGIN = "login";
    private static final String URL_UNAUTHORIZED = "unauthorized";

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        //先判断带参数的权限判断
        Subject subject = getSubject(request, response);
        if(null != mappedValue){
            String[] arra = (String[])mappedValue;
            for (String permission : arra) {
                if(subject.isPermitted(permission)){
                    return Boolean.TRUE;
                }
            }
        }
        HttpServletRequest httpRequest = ((HttpServletRequest)request);
        String uri = httpRequest.getRequestURI();//获取URI
        String basePath = httpRequest.getContextPath();//获取basePath
        if(null != uri && uri.startsWith(basePath)){
            uri = uri.replace(basePath, "");
        }
        if(StringUtils.isNotBlank(getSuffix())){
            uri = uri.replace(getSuffix(), "");
        }
        if(subject.isPermitted(uri)){
            return Boolean.TRUE;
        }
        if(RequestUtils.isAjaxRequest((HttpServletRequest) request)){
            LoggerUtils.debug(getClass(), "当前用户没有权限，Ajax请求！");
            JsonUtils.write((HttpServletResponse) response, ReturnUtils.UNAUTHORIZED);
        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (null == subject.getPrincipal()) {
            //表示没有登录，重定向到登录页面
            saveRequest(request);
            WebUtils.issueRedirect(request, response, StringUtils.isNotBlank(getLoginUrl())?getLoginUrl().trim():URL_LOGIN);
        } else {
            if (StringUtils.isNotBlank(StringUtils.isNotBlank(getUnauthorizedUrl())?getUnauthorizedUrl().trim():URL_UNAUTHORIZED)) {//如果有未授权页面跳转过去
                WebUtils.issueRedirect(request, response, StringUtils.isNotBlank(getUnauthorizedUrl())?getUnauthorizedUrl().trim():URL_UNAUTHORIZED);
            } else {//否则返回401未授权状态码
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
        return Boolean.FALSE;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    @Override
    public String getLoginUrl() {
        return loginUrl;
    }

    @Override
    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public String getUnauthorizedUrl() {
        return unauthorizedUrl;
    }

    public void setUnauthorizedUrl(String unauthorizedUrl) {
        this.unauthorizedUrl = unauthorizedUrl;
    }
}
